<template>
  <div class="role-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon"><UserFilled /></el-icon>
        <span>角色管理</span>
      </div>
      <div class="page-description">
        管理系统角色信息，包括角色的增删改查、状态管理等操作
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Search /></el-icon>
            <span>搜索条件</span>
          </div>
        </div>
      </template>
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
            :prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input
            v-model="searchForm.roleCode"
            placeholder="请输入角色编码"
            clearable
            style="width: 200px"
            :prefix-icon="Key"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-wrapper">
        <div class="left-operations">
          <!-- 新增角色按钮 -->
          <el-button 
            type="primary" 
            @click="handleAdd" 
            :icon="Plus"
          >
            新增角色
          </el-button>
          
          <!-- 批量启用按钮 -->
          <el-button 
            type="success" 
            @click="handleBatchEnable" 
            :icon="Check" 
            :disabled="!hasSelected"
          >
            批量启用
          </el-button>
          
          <!-- 批量禁用按钮 -->
          <el-button 
            type="warning" 
            @click="handleBatchDisable" 
            :icon="Close" 
            :disabled="!hasSelected"
          >
            批量禁用
          </el-button>
          
          <!-- 批量删除按钮 -->
          <el-button 
            type="danger" 
            @click="handleBatchDelete" 
            :icon="Delete" 
            :disabled="!hasSelected"
          >
            批量删除
          </el-button>
        </div>
        <div class="right-operations">
          <el-button @click="handleRefresh" :icon="Refresh" circle />
        </div>
      </div>
    </el-card>

    <!-- 角色表格 -->
    <el-card class="table-card" shadow="never">

      
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><List /></el-icon>
            <span>角色列表</span>
            <el-tag type="info" size="small">{{ pagination.total }} 条记录</el-tag>
          </div>
          <div class="header-right">
            <el-switch
              v-model="tableConfig.stripe"
              active-text="斑马纹"
              inactive-text="普通"
              size="small"
            />
            <el-switch
              v-model="tableConfig.border"
              active-text="边框"
              inactive-text="无边框"
              size="small"
            />
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="roleList"
        :border="tableConfig.border"
        :stripe="tableConfig.stripe"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column prop="roleName" label="角色名称" min-width="150" />
        <el-table-column prop="roleCode" label="角色编码" min-width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark">
              <el-icon v-if="row.status === 1"><Check /></el-icon>
              <el-icon v-else><Close /></el-icon>
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissionNames" label="权限" min-width="200">
          <template #default="{ row }">
            <div class="permission-tags">
              <el-tag
                v-for="permissionName in row.permissionNames"
                :key="permissionName"
                type="info"
                size="small"
                effect="plain"
              >
                {{ permissionName }}
              </el-tag>
              <el-tag v-if="!row.permissionNames || row.permissionNames.length === 0" type="warning" size="small" effect="plain">
                无权限
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" min-width="80" align="center" />
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="{ row }">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDateTime(row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <!-- 分配权限按钮 -->
              <el-tooltip content="分配权限" placement="top">
                <el-button 
                  type="success" 
                  size="small" 
                  circle
                  @click="openAssignDialog(row)" 
                  :icon="Key"
                />
              </el-tooltip>
              
              <!-- 编辑角色按钮 -->
              <el-tooltip content="编辑角色" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  circle
                  @click="handleEdit(row)" 
                  :icon="Edit"
                />
              </el-tooltip>
              
              <!-- 启用/禁用角色按钮 -->
              <el-tooltip :content="row.status === 1 ? '禁用角色' : '启用角色'" placement="top">
                <el-button
                  :type="row.status === 1 ? 'warning' : 'success'"
                  size="small"
                  circle
                  @click="handleToggleStatus(row)"
                  :icon="row.status === 1 ? Close : Check"
                />
              </el-tooltip>
              
              <!-- 查看详情按钮 -->
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  circle
                  @click="handleView(row)" 
                  :icon="View"
                />
              </el-tooltip>
              
              <!-- 删除角色按钮 -->
              <el-tooltip content="删除角色" placement="top">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="handleDelete(row)" 
                  :icon="Delete"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="7"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
        class="role-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input 
                v-model="roleForm.roleName" 
                placeholder="请输入角色名称"
                :prefix-icon="UserFilled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色编码" prop="roleCode">
              <el-input 
                v-model="roleForm.roleCode" 
                placeholder="请输入角色编码"
                :prefix-icon="Key"
                :disabled="!!roleForm.id"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="roleForm.status">
                <el-radio :label="1">
                  <el-icon><Check /></el-icon>
                  启用
                </el-radio>
                <el-radio :label="0">
                  <el-icon><Close /></el-icon>
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number 
                v-model="roleForm.sortOrder" 
                :min="0" 
                :max="999"
                placeholder="请输入排序值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      :title="`分配权限：${assignRole?.roleName || ''}`"
      width="700px"
      :close-on-click-modal="false"
    >
      <div class="assign-permission">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          node-key="id"
          show-checkbox
          default-expand-all
          check-strictly
          :props="{ label: 'permissionName', children: 'children' }"
          :default-checked-keys="checkedPermissionIds"
        />
      </div>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign" :loading="assignLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 角色详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="角色详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentRole" class="role-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色ID">{{ currentRole.id }}</el-descriptions-item>
          <el-descriptions-item label="角色名称">{{ currentRole.roleName }}</el-descriptions-item>
          <el-descriptions-item label="角色编码">{{ currentRole.roleCode }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentRole.status === 1 ? 'success' : 'danger'">
              {{ currentRole.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ currentRole.sortOrder }}</el-descriptions-item>
          <el-descriptions-item label="权限" :span="2">
            <el-tag
              v-for="permissionName in currentRole.permissionNames"
              :key="permissionName"
              type="info"
              size="small"
              style="margin-right: 5px"
            >
              {{ permissionName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色描述" :span="2">
            {{ currentRole.description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(currentRole.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatDateTime(currentRole.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  UserFilled, Search, Refresh, Plus, Check, Close, Delete, 
  List, Edit, View, Clock, Key 
} from '@element-plus/icons-vue'
import { roleApi } from '@/api/role'
import { permissionApi } from '@/api/permission'
import { useAuthStore } from '@/stores/auth'

// 获取权限存储
const authStore = useAuthStore()

// 权限检查方法
const hasPermission = (permission) => {
  return authStore.hasPermission(permission)
}

// 检查是否有任何权限
const hasAnyPermission = (permissions) => {
  return authStore.hasAnyPermission(permissions)
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const roleFormRef = ref()
const selectedRoles = ref([])
const currentRole = ref(null)

// 分配权限相关
const assignDialogVisible = ref(false)
const assignLoading = ref(false)
const assignRole = ref(null)
const permissionTreeRef = ref()
const permissionTree = ref([])
const checkedPermissionIds = ref([])

// 表格配置
const tableConfig = reactive({
  stripe: true,
  border: true
})

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleCode: '',
  status: null
})

// 角色表单
const roleForm = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  status: 1,
  sortOrder: 0
})

// 表单验证规则
const roleFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '角色编码长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '角色描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 角色列表
const roleList = ref([])

// 计算属性
const hasSelected = computed(() => selectedRoles.value.length > 0)

// 生命周期
onMounted(() => {
  fetchRoleList()
})

// 获取所有权限，构建树（基于parentId）
const loadPermissionTree = async () => {
  const res = await permissionApi.getAllPermissions()
  if (res.data.code === 200) {
    const list = res.data.data || []
    // 构建树形结构
    const map = new Map()
    list.forEach(item => { item.children = []; map.set(item.id, item) })
    const roots = []
    list.forEach(item => {
      if (item.parentId && map.get(item.parentId)) {
        map.get(item.parentId).children.push(item)
      } else {
        roots.push(item)
      }
    })
    permissionTree.value = roots
  }
}

// 打开分配权限对话框
const openAssignDialog = async (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有分配权限的权限')
    return
  }
  
  assignRole.value = row
  assignDialogVisible.value = true
  
  // 先加载权限树
  await loadPermissionTree()
  
  // 获取角色当前权限
  const resp = await roleApi.getRolePermissionIds(row.id)
  if (resp.data.code === 200) {
    const allPermissionIds = resp.data.data || []
    
    // 设置选中的权限ID
    checkedPermissionIds.value = allPermissionIds
    
    // 等待DOM更新后设置选中状态
    await nextTick()
    
    // 设置权限树的选中状态
    if (permissionTreeRef.value) {
      // 先清除所有选中状态
      permissionTreeRef.value.setCheckedKeys([])
      // 再设置新的选中状态
      permissionTreeRef.value.setCheckedKeys(checkedPermissionIds.value)
    }
  }
}

// 提交分配权限
const submitAssign = async () => {
  try {
    assignLoading.value = true
    // 由于使用了check-strictly，直接获取选中的节点即可
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    
    console.log('用户选择的权限ID:', checkedKeys)
    
    const res = await roleApi.assignPermissions(assignRole.value.id, checkedKeys)
    if (res.data.code === 200) {
      ElMessage.success('分配权限成功')
      assignDialogVisible.value = false
      fetchRoleList()
    } else {
      ElMessage.error(res.data.message || '分配权限失败')
    }
  } catch (e) {
    console.error('分配权限失败', e)
    ElMessage.error('分配权限失败')
  } finally {
    assignLoading.value = false
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      orderBy: 'id',
      orderType: 'asc',
      ...searchForm
    }
    
    const response = await roleApi.getRoleList(params)
    if (response.data.code === 200) {
      roleList.value = response.data.data.list
      pagination.total = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchRoleList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    roleName: '',
    roleCode: '',
    status: null
  })
  pagination.pageNum = 1
  fetchRoleList()
}

// 刷新
const handleRefresh = () => {
  fetchRoleList()
  ElMessage.success('刷新成功')
}

// 新增角色
const handleAdd = () => {
  // 检查新增权限
  if (!authStore.hasPermission('system:role:add')) {
    ElMessage.warning('您没有新增角色的权限')
    return
  }
  
  dialogTitle.value = '新增角色'
  resetRoleForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有编辑角色的权限')
    return
  }
  
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, {
    id: row.id,
    roleName: row.roleName,
    roleCode: row.roleCode,
    description: row.description,
    status: row.status,
    sortOrder: row.sortOrder
  })
  dialogVisible.value = true
}

// 查看角色详情
const handleView = (row) => {
  // 检查查询权限
  if (!authStore.hasPermission('system:role:query')) {
    ElMessage.warning('您没有查看角色详情的权限')
    return
  }
  
  currentRole.value = row
  detailDialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  // 检查删除权限
  if (!authStore.hasPermission('system:role:delete')) {
    ElMessage.warning('您没有删除角色的权限')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    const response = await roleApi.deleteRole(row.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchRoleList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换角色状态
const handleToggleStatus = async (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有修改角色状态的权限')
    return
  }
  
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}角色 "${row.roleName}" 吗？`,
      `确认${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.updateRoleStatus(row.id, newStatus)
    if (response.data.code === 200) {
      ElMessage.success(`${statusText}成功`)
      fetchRoleList()
    } else {
      ElMessage.error(response.data.message || `${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}角色失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 批量操作
const handleBatchEnable = async () => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有批量启用角色的权限')
    return
  }
  await handleBatchStatus(1, '启用')
}

const handleBatchDisable = async () => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有批量禁用角色的权限')
    return
  }
  await handleBatchStatus(0, '禁用')
}

const handleBatchStatus = async (status, statusText) => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请先选择要操作的角色')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}选中的 ${selectedRoles.value.length} 个角色吗？`,
      `批量${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = selectedRoles.value.map(role => 
      roleApi.updateRoleStatus(role.id, status)
    )
    
    await Promise.all(promises)
    ElMessage.success(`批量${statusText}成功`)
    fetchRoleList()
    selectedRoles.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`批量${statusText}失败:`, error)
      ElMessage.error(`批量${statusText}失败`)
    }
  }
}

const handleBatchDelete = async () => {
  // 检查删除权限
  if (!authStore.hasPermission('system:role:delete')) {
    ElMessage.warning('您没有批量删除角色的权限')
    return
  }
  
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请先选择要删除的角色')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    const promises = selectedRoles.value.map(role => 
      roleApi.deleteRole(role.id)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    fetchRoleList()
    selectedRoles.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    submitLoading.value = true
    
    const api = roleForm.id ? roleApi.updateRole : roleApi.addRole
    const response = await api(roleForm)
    
    if (response.data.code === 200) {
      ElMessage.success(roleForm.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchRoleList()
    } else {
      ElMessage.error(response.data.message || (roleForm.id ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置角色表单
const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: null,
    roleName: '',
    roleCode: '',
    description: '',
    status: 1,
    sortOrder: 0
  })
  nextTick(() => {
    roleFormRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetRoleForm()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchRoleList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchRoleList()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.role-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.title-icon {
  margin-right: 10px;
  font-size: 28px;
}

.page-description {
  font-size: 14px;
  opacity: 0.9;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-icon {
  font-size: 16px;
  color: var(--el-color-primary);
  margin-right: 2px;
}

.card-header .header-left span {
  font-weight: 500;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.operation-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.right-operations {
  display: flex;
  gap: 10px;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.operation-buttons .el-button {
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.operation-buttons .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.operation-buttons .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
}

.operation-buttons .el-button--success {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
}

.operation-buttons .el-button--success:hover {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
}

.operation-buttons .el-button--warning {
  background: linear-gradient(135deg, #e6a23c 0%, #cf9236 100%);
  border: none;
}

.operation-buttons .el-button--warning:hover {
  background: linear-gradient(135deg, #cf9236 0%, #b88230 100%);
}

.operation-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #82848a 100%);
  border: none;
}

.operation-buttons .el-button--info:hover {
  background: linear-gradient(135deg, #82848a 0%, #73767a 100%);
}

.operation-buttons .el-button--danger {
  background: linear-gradient(135deg, #f56c6c 0%, #dc4e4e 100%);
  border: none;
}

.operation-buttons .el-button--danger:hover {
  background: linear-gradient(135deg, #dc4e4e 0%, #c23e3e 100%);
}

/* 操作列样式优化 */
:deep(.el-table .el-table__cell:last-child) {
  padding: 8px 12px;
}

:deep(.el-table .el-table__cell:last-child .cell) {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 工具提示样式优化 */
:deep(.el-tooltip__popper) {
  font-size: 12px;
  padding: 6px 10px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
  --el-pagination-button-margin: 0 4px;
  --el-pagination-button-padding: 0 8px;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin: 0 16px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: var(--el-color-primary);
  color: white;
  font-weight: 600;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

.role-form {
  padding: 20px 0;
}

.role-detail {
  padding: 20px 0;
}

.assign-permission {
  max-height: 400px;
  overflow: auto;
  padding: 10px 5px;
  border: 1px solid #eee;
  border-radius: 6px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__header-wrapper) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table .el-table__body td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 10px;
  }
  
  .operation-wrapper {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-operations,
  .right-operations {
    width: 100%;
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 